package cn.wrl.cart.service.impl;

import cn.wrl.cart.service.ShopCartService;
import cn.wrl.pojo.IMOOCJSONResult;
import cn.wrl.pojo.ShopcartBO;
import cn.wrl.service.BaseService;
import cn.wrl.utils.JsonUtils;
import cn.wrl.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.wrl.controller.BaseController.FOODIE_SHOPCART;

@RestController
public class ShopCartServiceImpl extends BaseService implements ShopCartService {

    @Autowired
    private RedisOperator redisOperator;

    @Override
    public IMOOCJSONResult add(String userId, ShopcartBO shopcartBO) {
        String shopcartListCache = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        List<ShopcartBO> shopcartBOList = null;
        if (StringUtils.isNoneBlank(shopcartListCache)) {
            shopcartBOList = JsonUtils.jsonToList(shopcartListCache, ShopcartBO.class);
            //判断新加的商品是否在购物车中。默认false
            boolean isInShopcartBOList = false;
            for (ShopcartBO sc : shopcartBOList) {
                if (sc.getSpecId().equals(shopcartBO.getSpecId())) {
                    sc.setBuyCounts(sc.getBuyCounts() + shopcartBO.getBuyCounts());
                    isInShopcartBOList = true;
                    break;
                }
            }
            if (!isInShopcartBOList) {
                shopcartBOList.add(shopcartBO);
            }
        } else {
            shopcartBOList = new ArrayList<>();
            shopcartBOList.add(shopcartBO);
        }
        redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartBOList));
        return IMOOCJSONResult.ok();
    }

    @Override
    public IMOOCJSONResult del(String userId, String itemSpecId) {
        String shopcartListCache = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
        List<ShopcartBO> shopcartBOList = null;
        if (StringUtils.isNoneBlank(shopcartListCache)) {
            shopcartBOList = JsonUtils.jsonToList(shopcartListCache, ShopcartBO.class);
            shopcartBOList = shopcartBOList.stream()
                    .filter(e -> !e.getSpecId().equals(itemSpecId))
                    .collect(Collectors.toList());
            redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartBOList));
        }
        return IMOOCJSONResult.ok();
    }

    @Override
    public IMOOCJSONResult clear(String userId) {
        redisOperator.del(FOODIE_SHOPCART + ":" + userId);
        return IMOOCJSONResult.ok();
    }
}
